//index.js
//获取应用实例
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickname: "",
    userPic: "",
    index: 1,
    num: 1,
    page: 0, //获取分页第几页
    text: "附近",
    inputText: "",
    orderList: [],
    time: [],
    orderId: null,
    latitude: null,
    longitude: null,
    state: 0,
    site: 1,
    distance: null,
    cateId: -1,
    orderListTwo: [],
    status: 5,
    orderCount: null,
    orderText: '',
    number: 0,
    count: 0,
    start: 0,
    rate: 0,
    complaintCount: 0,
    title: 'personal',
    picSite: 1,
    selectPic: 0,
    loadingHidden: true,
    skill: 0,
    mark: '',
    person: 0,
    name: "",
    book: 0,
    rate: 0,
    level: 1,
    starts: 0,
    list: [{
        iconPath: "../../icons/l1-07.png",
        selectedIconPath: "../../icons/l1-07-pre.png",
        selectedColor: "#4EDF80",
        active: true


      },
      {
        iconPath: "../../icons/l1-04.png",
        selectedIconPath: "../../icons/l1-04-pre.png",
        selectedColor: "#4EDF80",
        active: false
      },
      {
        iconPath: "../../icons/l1-06.png",
        selectedIconPath: "../../icons/l1-06-pre.png",
        selectedColor: "#4EDF80",
        active: false
      }
    ],
    approvePhone: 1
  },

  /**
   * 抢单列表请求
   */
  orderList: function() {
    let that = this;

    if (this.data.orderList.length == 0) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
    }
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {


      wx.request({
        url: 'https://www.xiaozheng8.com/serviceOrder/findAllGrab/v4',
        method: "post",
        data: {
          page: 0,
          size: 10,
        },
        success: function(res) {
          console.log(res)
          console.log('--------------第一次第一次-----------------')
          if (res.data.code == 200) {
            that.setData({
              orderList: res.data.data,
            })
            console.log(that.data.orderList)
            // var orderList=[];
            // for (var i = 0; i < that.data.orderList.length; i++) {
            //   console.log(that.data.orderList[i].grabStatus);
            //   if (that.data.orderList[i].grabStatus == 2) {
            //     console.log(that.data.orderList[i])
            //     orderList.push(that.data.orderList[i])
            //   }
            // }
            // console.log(orderList)
            // that.setData({
            //   orderList: orderList
            // });

          }
        },
      });
    } else {
      wx.getSetting({
        success: (res) => {
          console.log(res);
          if (!res.authSetting['scope.userLocation'])
            app.openConfirm();
            return false;
        }, fail(res) {
          console.log(res);
          return false;
        }
      })
      wx.getLocation({
        type: 'wgs84',
        success: function(res) {
          wx.request({
            url: 'https://www.xiaozheng8.com/serviceOrder/findAllGrab/v3',
            method: "post",
            data: {
              lat: res.latitude,
              lng: res.longitude,
              userId: wx.getStorageSync("userId"),
              page: 0,
              size: 10,
            },
            success: function(res) {
              console.log(res)
              console.log('--------------第一次第一次-----------------')
              if (res.data.code == 200) {
                that.setData({
                  orderList: res.data.data,
                })
                console.log(that.data.orderList)
              }
            }
          })
        }

      })

    }
  },




  go: function(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    // this.approve();
    this.setData({
      site: index + 1,
      selectPic: index,
      page: 0
    });
    if (that.data.site == 1) {
      this.orderList();
      wx.setNavigationBarTitle({
        title: '抢单',
      })
      // this.approve();
    }
    if (that.data.site == 2) {
      this.orderListTwo();
      wx.setNavigationBarTitle({
        title: "订单",
      })
    }
    if (that.data.site == 3) {
      wx.setNavigationBarTitle({
        title: '我的',
      })
      this.approve();
    }


  },

  /**
   * 订单列表请求
   */
  orderListTwo: function(options) {
    let that = this;
    if (this.data.orderListTwo.length == 0) {
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true
      })
    }
    console.log(wx.getStorageSync("userId"))
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindAll/v2',
      method: 'post',
      data: {
        userId: wx.getStorageSync("userId"),
        page: 0,
        size: 10,
      },
      success: function(res) {
        console.log(res);
        if (res.data == "") {
          return false
        }
        if (res.data.code === 200) {
          console.log(res.data.data)
          console.log("====")
          that.setData({
            orderListTwo: res.data.data,
            orderCount: res.data.data.length,
          })

        }
      }
    })
  },

  // 用户微信登录
  getUserInfo() {
    var that = this;
    wx.getUserInfo({
      success: function(res) {
        console.log(res);
        wx.setStorage({
          key: 'info',
          data: res,
        })
        that.setData({
          nickname: res.userInfo.nickName,
          userPic: res.userInfo.avatarUrl

        })
        wx.request({
          url: 'https://www.xiaozheng8.com/user/login',
          data: {
            code: app.globalData.code,
            iv: res.iv,
            encryptedData: res.encryptedData
          },
          method: "post",
          success(req) {
            console.log(req)
            wx.setStorageSync("userId", req.data.data.userId)
            app.globalData.myUserInfo = true;
            that.approve();
            that.postHeader(that.data.userPic, that.data.nickname, req.data.data.userId);
          },
          fail(req) {
            console.log(req)
          }
        })
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },
  // 上传头像，昵称
  postHeader(header, name, userId) {
    wx.request({
      url: 'https://www.xiaozheng8.com/user/update',
      data: {
        userId: userId,
        headImg: header,
        nickName: name,
        mark: ""
      },
      method: 'post',
      success: function(res) {
        console.log(res);
      },
      fail: function(res) {
        console.log(res);
      },
      complete: function(res) {},
    })
  },
  // 认证
  approve: function() {
    let that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/receiveUser/findById',
      method: "post",
      data: {
        userId: wx.getStorageSync("userId"),
      },
      success: function(res) {
        console.log(res);
        if (res.data == "") {
          return false
        }
        console.log(that.data.skill);
        console.log(that.data.person);
        console.log(that.data.book);
        that.setData({
          mark: res.data.data.mark,
          rate: res.data.data.rate,
          starts: res.data.data.starts,
          complaintCount: res.data.data.complaintCount

        })
        console.log(res.data.data.authStatus);

        var skill = res.data.data.authStatus.substr(0, 1);
        var person = res.data.data.authStatus.substr(1, 1);
        var book = res.data.data.authStatus.substr(2, 1);
        that.setData({
          skill: skill,
          person: person,
          book: book,
        })
      },
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    let isIphoneX = app.globalData.isIphoneX;
    this.setData({
      isIphoneX: isIphoneX
    });

    wx.request({
      url: 'https://www.xiaozheng8.com/signFind?userId=' + wx.getStorageSync("userId"),
      data: {
        userId: wx.getStorageSync("userId")
      },
      method: "post",
      success(res) {
        console.log(res);
      }
    })
    if (options.name == "" || options.name == undefined) {

    } else {
      this.setData({
        name: options.name
      })
    };
    console.log(options)
    wx.getStorage({
      key: 'info',
      success: function(res) {
        console.log(res.data.userInfo);
        that.setData({
          nickname: res.data.userInfo.nickName,
          userPic: res.data.userInfo.avatarUrl

        })
        app.globalData.myUserInfo = true;
      },
    })
    // this.searchList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.editTabBar();
    // if (app.globalData.phone == null || app.globalData.phone == "") {
    //   wx.navigateTo({
    //     url: '../bind/bind?binded=' + 0,
    //   })
    //   return false
    // }
    // if (wx.getStorageSync("userId") == 0) {
    //   wx.navigateTo({
    //     url: '../bind/bind?binded=' + 0,
    //   })
    //   return false
    // }
    this.setData({
      msgList: [{
          title: "隔壁老王发了1个订单",
          time: "12:00"
        },
        {
          title: "李师傅抢了隔壁老王的订单",
          time: "12:10"
        },
        {
          title: "隔壁老王同意了李师傅的接单",
          time: "12:20"
        }
      ]
    });
    var that = this;
    if (this.data.name == "" || this.data.name == undefined) {
      that.orderList();
    } else {
      // that.searchList()
    }
    this.orderListTwo();
    this.approve();
  },

  /**
   * 筛选事件
   */
  screen: function() {
    wx.navigateTo({
      url: '../screen/screen',
    })
    this.setData({
      isRuleTrue: false,
      index: 0,
    })
  },

  /**
   * 综合事件
   */
  comprehensive: function() {
    this.setData({
      isRuleTrue: false,
      index: 0,
    })
  },

  translate: function(e) {
    // console.log(e);
    this.setData({
      isRuleTrue: true,
      index: 0,
    })

  },

  success: function() {
    this.setData({
      isRuleTrue: false,
      index: 1
    })
  },

  changeBgc: function(e) {
    this.setData({
      num: e.target.dataset.num,
      //   isRuleTrue: false,
      index: 0,
    })
  },

  sreach: function() {
    this.setData({
      isTrue: true,
    })
  },

  text: function(e) {
    let that = this;
    // console.log(e);
    that.setData({
      text: e.target.dataset.text
    })
  },

  /**
   * 切换身份事件
   */
  change: function() {
    wx.navigateTo({
      url: '../changeId/changeId',
    })
    wx.setStorageSync("type", null);
  },

  /**
   * 设置事件
   */
  toSetting: function() {
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../receivingSetting/receivingSetting',
      })
    }
  },

  /**
   * 进入身份认证事件函数
   */
  technology: function() {
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../technology/technology',
      })
    }
  },

  /**
   * 进入服务内容事件函数
   */
  server: function() {
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../receivingServer/receivingServer',
      })
    }
  },

  /**
   * 进入搜索
   */
  search: function() {
    wx.navigateTo({
      url: '../receivingSearch/receivingSearch',
    })
  },

  /**
   * 抢单事件函数
   */
  toMyOrder: function(e) {
    var that = this;
    // this.approve();
    console.log("---houmian--")
    console.log(that.data.skill)
    var info = "";
    if (that.data.skill == null || that.data.skill == "" || that.data.skill == undefined || that.data.skill == 0 || that.data.skill == 1 || that.data.skill == 9) {
      info = " '服务内容' ";
    }
    if (that.data.person == null || that.data.person == "" || that.data.person == undefined || that.data.person == 0 || that.data.person == 1 || that.data.person == 9) {
      info = info + " '身份认证' ";
    }
    if (that.data.book == null || that.data.book == "" || that.data.book == undefined || that.data.book == 0 || that.data.book == 1 || that.data.book == 9) {
      info = info + " '技能证书' ";
    }
    var that = this;

    if (info.length > 0) {
      wx.showModal({
        title: "提示",
        content: '请您进入个人中心完善' + info + "后再来抢单哦",
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            that.setData({
              site: 3,
              selectPic: 2
            })
            wx.setNavigationBarTitle({
              title: '我的',
            })
          }
        }
      })
      return;
    } else {

      // console.log(e)
      that.setData({
        publishId: e.currentTarget.dataset.publishid,
        distance: e.currentTarget.dataset.distance
      })
      // console.log(e.currentTarget.dataset.orderid)

      wx.navigateTo({
        url: '../grabOrder/grabOrder?publishId=' + that.data.publishId + '&distance=' + that.data.distance,
      })
      console.log(that.data.publishId)
    }

  },

  /**
   * 筛选未完成订单
   */
  unFinish: function() {
    wx.navigateTo({
      url: '../unfinish/unfinish',
    })
  },

  /**
   * 空白页面去抢单事件
   */
  goGrabOrder: function() {
    this.setData({
      site: 1,
      selectPic: 0,
    })
  },


  /**
   * 请求抢单列表下一页
   */
  nextOrderPage: function() {
    let that = this;
    wx.getSetting({
      success: (res) => {
        console.log(res);
        if (!res.authSetting['scope.userLocation'])
          app.openConfirm();
        return false;
      }, fail(res) {
        console.log(res);
        return false;
      }
    })
    
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        wx.request({
          url: 'https://www.xiaozheng8.com/serviceOrder/findAllGrab/v3',
          method: "post",
          data: {
            lat: res.latitude,
            lng: res.longitude,
            userId: wx.getStorageSync("userId"),
            page: that.data.page + 1,
            size: 10,
          },
          // wx.request({
          //   url: 'https://www.xiaozheng8.com/serviceOrder/findAllGrab/v3',
          //   method: "post",
          //   data: {
          //     cateId: that.data.cateId,
          //     userId: wx.getStorageSync("userId"),

          //     size: 10,
          //   },
          success: function(res) {
            console.log(res.data.data)
            console.log("page" + ++that.data.page)
            console.log('-------------------------------')
            if (res.data.code == 200) {
              console.log(res.data.data);
              console.log(that.data.orderList);
              that.setData({
                page: that.data.page + 1,
                orderList: that.data.orderList.concat(res.data.data),
              });

            }
          },
        });
      }
    })
  },
  nextOrderPageNoId() {
    let that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/findAllGrab/v4',
      method: "post",
      data: {
        page: that.data.page + 1,
        size: 10,
      },
      success: function(res) {
        console.log(res.data.data)
        console.log("page" + ++that.data.page)
        console.log('-------------------------------')
        if (res.data.code == 200) {
          console.log(res.data.data);
          console.log(that.data.orderList);
          that.setData({
            page: that.data.page + 1,
            orderList: that.data.orderList.concat(res.data.data),
          });

        }
      },
    });
  },

  /**
   * 进入订单详情
   */
  detail: function(e) {

    var that = this;
    console.log(e + "zzzz")

    that.setData({
      orderId: e.currentTarget.dataset.orderid,
    })
    var publishId = e.currentTarget.dataset.publishid;
    var distance = e.currentTarget.dataset.distance;
    var grabStatus = e.currentTarget.dataset.grabstatus;
    console.log(that)
    if (that.data.orderId == null) {
      wx.navigateTo({
        url: '../failOrder/failOrder?publishId=' + publishId + '&distance=' + distance + "&grab=" + true + "&grabStatus=" + grabStatus,
      })
    } else {
      wx.navigateTo({
        url: '../grabSuccess/grabSuccess?orderId=' + that.data.orderId,
      })

    }

  },

  /**
   * 已抢订单无法点击弹窗事件
   */
  noClick: function() {
    wx.showModal({
      title: '提示',
      content: '该订单已经被抢走了',
      confirmText: '确定',
      confirmColor: '#0bbd79',
      showCancel: false
    })
  },

  /**
   * 请求订单列表下一页
   */
  nextMinePage: function() {
    let that = this;
    wx.request({
      url: 'https://www.xiaozheng8.com/serviceOrder/receiveFindAll/v2',
      method: 'post',
      data: {
        userId: wx.getStorageSync("userId"),
        page: that.data.page + 1,
        size: 10,
      },
      success: function(res) {
        console.log(res);

        // console.log(that.data.page)
        if (res.data.code === 200) {
          that.setData({
            page: that.data.page + 1,
            orderListTwo: that.data.orderListTwo.concat(res.data.data),
          })
        }
      }
    })
  },

  /**
   * 进入我的订单
   */
  order: function(e) {
    let a = e.currentTarget.dataset.class;
    wx.navigateTo({
      url: '../myOrder/myOrder?userId=' + wx.getStorageSync("userId") + '&class=' + a,
    })
  },

  /**
   * 进入身份认证
   */
  user: function() {
    // if (this.data.title = "personal") {
    // console.log(this.data.title)
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../personal/personal'
      })
    }
    // } else {
    //   wx.navigateTo({
    //     url: '../enterprise/enterprise',
    //   })
    // }

  },
  // 钱包
  money: function() {
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../withdraw/withdraw',
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })
    }
  },
  // 进入签到
  sign() {
    if (this.data.userPic == "") {
      wx.showToast({
        title: '请先点击登录',
        icon: "none"
      })
    } else {
      wx.navigateTo({
        url: '../sign/sign',
      })
    }

  },
  // 进入绑定手机
  bindPhone() {
    wx.navigateTo({
      url: '../bind/bind',
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    if (that.data.site == 1) {
      // 抢单列表触底事件
      if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId")) {
        that.nextOrderPageNoId();
      } else {
        that.nextOrderPage();
      }

    } else if (that.data.site == 2) {
      // 订单列表触底事件
      that.nextMinePage();
    }

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})